package com.filter;

import com.Util.IsNotNullUtil;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


public class CharacterEncodingFilter implements Filter {
    String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        //通过filterConfig对象获取web.xml中配置的编码集初始化参数
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将参数的请求和响应对象强转
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if (IsNotNullUtil.isNotNull(encoding)) {
            //将获取到的编码集设置给请求和响应对象
            resp.setCharacterEncoding(encoding);
            req.setCharacterEncoding(encoding);
        } else {
            resp.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            req.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
        //注意要记得放行
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}
